/*
-----------------------------------------------------------------------------
This source file is part of as4game
	(ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package org.as4game.common.data
{
	import flash.utils.Dictionary;
	

	/**
	 * 缓存<br>
	 * <li> 一种按 最久未使用 淘汰算法管理的数据字典, 数据可以为任意类型
	 * <li> 通过 getObject, addObject, removeObject 来进行数据操作
	 * <li> fn_dispose 设置当对象被淘汰时的操作
	 * <li> fixSize 用于释放/扩展缓冲区空间
	 */
	public class Cache
	{
		static private const MIN_COUNT:int = 2;
		
		private var _name:String;			// cache 名字
		private var _maxSize:int;			// 最大长度
		private var _initMaxSize:int;		// 最大长度初始值
		private var _list:List2;			// 列表, 维护最久未使用队列
		private var _dict:Dictionary;		// 哈希表
		
		// 回调函数
		public var fn_dispose:Function;	// 当对象被淘汰时调用, 原型: function fn( key, obj ):void;
		
		// ================================================================================
		
		/**
		 * 构造一个缓存, 一般不需要自动扩展即可满足要求
		 * 
		 * @param name 任意自定义名字
		 * @param initSize 可存放的数量, 该值可后期调整
		 */
		public function Cache(name:String=null, initSize:int=0){
			_name = name;
			_maxSize = Math.max( initSize, MIN_COUNT);
			_initMaxSize = _maxSize;
			_list = new List2;
			_dict = new Dictionary();
		}
		
		/**
		 * 清空
		 */
		public function clear():void{
			
			// dispose
			if( fn_dispose != null ){
				forEach( fn_dispose );
			}
			
			_list.clear( false );			// 不需要清空连接信息
			_dict = new Dictionary;
		}
		
		public function get name():String{
			return _name;
		}
		
		public function get count():int{
			return _list.count;
		}
		
		/**
		 * 最大缓存数量, 超过该数量的部分被释放, 可以设置 fn_extend 来控制动态增长
		 */
		public function get maxCount():int{
			return _maxSize;
		}
		public function set maxCount( value:int ):void{
			if( value < MIN_COUNT ) value = MIN_COUNT;
			if( _maxSize != value ){
				_maxSize = value;
				_check_size();
			}
		}
		
		/**
		 * 自动调整缓冲区尺寸
		 * @param bEnpty 是否自动缩小缓冲区
		 * @param bExtend 是否自动扩大缓冲区
		 */
		public function fixSize(bEmpty:Boolean=true, bExtend:Boolean=true):void{
			var count:int = _list.count;
			var max:int = _maxSize;
			
			if( bEmpty && max>_initMaxSize && count*2<max){
				max = Math.max(count / 2, _initMaxSize);			// empty
			}
			else if( bExtend && count>=max){
				max = count * 2;									// extend
			}
			
			if( max != _maxSize ){
				_check_size();
			}
		}
		
		
		/**
		 * 检测存在性
		 */
		public function has( key:Object ):Boolean {
			return _dict[ key ] != null;
		}
		
		/**
		 * 检索对象
		 * @param key 键
		 * @param bModifyPriority 是否修改优先级列表, 使得该对象不容易被释放
		 */
		public function getObject( key:Object, bModifyPriority:Boolean=true ):Object{
			var obj:Object = _dict[ key ];
			if( obj ){
				if( bModifyPriority) _list.moveToHead( obj );
				obj = obj.__data;
			}
			return obj;
		}
		
		
		/**
		 * 删除对象, 会激发 dispose 事件
		 */
		public function removeObject( key:Object ):Object{
			var obj:Object = _dict[ key ];
			if( obj ){
				_list.removeAt( obj );
				_dict[ key ] = null;
				delete _dict[ key ];
				
				// dispose
				if( fn_dispose != null ){
					fn_dispose( key, obj.__data );
				}
			}
			return obj;
		}

		/**
		 * 添加对象
		 */
		public function addObject( key:Object, value:Object ):void{
			removeObject( key );
			
			var obj:Object = { __key:key, __data:value };
			_list.pushHead( obj );
			_dict[ key ] = obj;
			
			if( _list.count > _maxSize ){
				_check_size();
			}
		}
		
		/**
		 * 获取最久未使用的对象
		 */
		public function getLastObject():Object{
			var obj:Object = _list.peekTail();
			return obj.__data;
		}
		
		/**
		 * 获取最新被使用的对象
		 */
		public function getFirstObject():Object{
			var obj:Object = _list.peekHead();
			return obj.__data;
		}
		
		/**
		 * 检测尺寸, 如果超出, 则删除最末尾的对象
		 */
		private function _check_size():void{
			while( _list.count > _maxSize ){
				var obj:Object = _list.peekTail();
				removeObject( obj.__key );
			}
		}
		
		/**
		 * 遍历对象执行操作
		 * @param fn 原型: function fn( key, obj ):void;
		 */
		public function forEach( fn:Function ):void{
			_list.forEach( function(obj:Object):void{
				fn( obj.__key, obj.__data );
			});
		}
		
		/**
		 */
		public function toString():String{
			var arr:Array = [ "[Cache] name=" + _name + ", count=" + count + ", maxSize=" + _maxSize ];
			forEach( function(key:Object, obj:Object):void{
				arr.push( obj );
			});
			var str:String = arr.join( "\r" );
			return str;
		}
	}
}